package org.bingo.misc;


import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class VideoUtil {
    private final String ffmpegPath;
    private final File tmpDir;
    private final String convertVideoArgs = " -i %s -c:v copy -c:a copy -strict -2 -f hls -hls_list_size 0 -hls_time 30 %s";
    private String ffmpegHome;

    public VideoUtil(String tmpDir, String ffmpegHome) {
        this.ffmpegHome = ffmpegHome;
        this.ffmpegPath = ffmpegHome +
                File.separator +
                "bin" +
                File.separator +
                "ffmpeg" +
                (System.getProperty("os.name").startsWith("Windows") ? ".exe" : "");
        this.tmpDir = new File(tmpDir);
        if (!this.tmpDir.exists()) {
            this.tmpDir.mkdir();
        }
    }

    private File randomTmpDir() {
        File parentDir = new File(tmpDir.getAbsolutePath() +
                File.separator +
                System.currentTimeMillis());
        if (!parentDir.exists()) {
            parentDir.mkdirs();
        }
        return parentDir;
    }

    public List<File> encodeVideoToM3u8AndTs(File src) throws Exception {
        String parentDir = randomTmpDir().getAbsolutePath();
        String output = parentDir
                + File.separator + src.getName().split("\\.")[0] + ".m3u8";
        String args = String.format(convertVideoArgs,
                src.getAbsolutePath(),
                output);

        Process process = Runtime.getRuntime().exec( ffmpegPath + args);
        Scanner scanner = new Scanner(process.getErrorStream());
        while (scanner.hasNextLine()) {
            scanner.nextLine();
        }
        if (process.waitFor() != 0) {
            process.destroy();
            throw new Exception("video convert error: " + process.exitValue());
        }
        process.destroy();
        List<File> fileList = new ArrayList<>();
        Files.list(Paths.get(parentDir)).forEach(path -> {
            fileList.add(path.toFile());
        });

        return fileList;
    }

}
